package com.example.javapracticaltraining.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.pojo.Users;
import com.example.javapracticaltraining.entity.pojo.Visitors;
import com.example.javapracticaltraining.entity.vo.request.VisitorRegistrationVO;
import com.example.javapracticaltraining.entity.vo.response.VisitorInfoVO;
import com.example.javapracticaltraining.service.UsersService;
import com.example.javapracticaltraining.service.VisitorsService;
import org.springframework.beans.BeanUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "来访管理", description = "提供来访者登记、查询、更新和删除功能")
@RestController
@RequestMapping("/visitors")
public class VisitorsController {

    @Autowired
    private VisitorsService visitorsService;

    @Autowired
    private UsersService usersService;

    @Operation(summary = "登记来访", description = "添加新的来访者记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "来访登记成功")
    })
    @PostMapping
    public R<String> addVisitor(@RequestBody VisitorRegistrationVO visitorVO) {
        // 将VO转换为实体
        Visitors visitor = new Visitors();
        visitor.setVisitorName(visitorVO.getVisitorName());
        visitor.setIdCardNumber(visitorVO.getIdCardNumber());
        visitor.setVisitTime(visitorVO.getVisitTime());
        visitor.setReason(visitorVO.getReason());

        // 根据被访人姓名查询对应的用户ID
        String visitedPersonName = visitorVO.getVisitedPersonName();
        if (visitedPersonName != null && !visitedPersonName.isEmpty()) {
            LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Users::getRealName, visitedPersonName);
            Users user = usersService.getOne(queryWrapper);
            if (user != null) {
                visitor.setVisitedUserId(user.getUserId());
            } else {
                // 如果找不到对应的用户，设置一个默认值
                visitor.setVisitedUserId(1); // 假设ID为1的用户是系统默认用户
            }
        } else {
            // 如果没有提供被访人姓名，设置一个默认值
            visitor.setVisitedUserId(1); // 假设ID为1的用户是系统默认用户
        }

        visitorsService.save(visitor);
        return R.success("来访登记成功");
    }

    @Operation(summary = "分页查询来访记录", description = "根据条件分页查询来访记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功")
    })
    @GetMapping("/page")
    public R<Page<VisitorInfoVO>> getVisitorsByPage(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页记录数", example = "10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "来访者姓名，支持模糊查询") String visitorName,
            @Parameter(description = "身份证号码，精确匹配") String idCardNumber) {

        // 创建分页对象，设置当前页和每页大小
        Page<Visitors> pageInfo = new Page<>();
        pageInfo.setCurrent(page);
        pageInfo.setSize(pageSize);

        // 创建查询条件
        LambdaQueryWrapper<Visitors> queryWrapper = new LambdaQueryWrapper<>();

        if (visitorName != null && !visitorName.isEmpty()) {
            queryWrapper.like(Visitors::getVisitorName, visitorName);
        }
        if (idCardNumber != null && !idCardNumber.isEmpty()) {
            queryWrapper.eq(Visitors::getIdCardNumber, idCardNumber);
        }

        // 执行分页查询
        visitorsService.page(pageInfo, queryWrapper);

        // 将Visitors实体转换为VisitorInfoVO
        Page<VisitorInfoVO> voPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, voPage, "records");

        voPage.setRecords(pageInfo.getRecords().stream().map(visitor -> {
            VisitorInfoVO vo = new VisitorInfoVO();
            BeanUtils.copyProperties(visitor, vo);

            // 根据visitedUserId查询用户信息，设置被访人姓名
            Integer visitedUserId = visitor.getVisitedUserId();
            if (visitedUserId != null) {
                Users user = usersService.getById(visitedUserId);
                if (user != null) {
                    vo.setVisitedPersonName(user.getRealName());
                }
            }

            return vo;
        }).collect(java.util.stream.Collectors.toList()));

        return R.success(voPage);
    }

    @Operation(summary = "删除来访记录", description = "根据ID删除来访记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "来访记录删除成功")
    })
    @DeleteMapping("/{visitorId}")
    public R<String> deleteVisitor(
            @Parameter(description = "来访记录ID", required = true) @PathVariable Integer visitorId) {
        visitorsService.removeById(visitorId);
        return R.success("来访记录删除成功");
    }

    @Operation(summary = "更新来访记录", description = "更新已有的来访记录信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "来访记录更新成功")
    })
    @PutMapping
    public R<String> updateVisitor(@RequestBody VisitorInfoVO visitorInfoVO) {
        // 将VO转换为实体
        Visitors visitor = new Visitors();
        visitor.setVisitorId(visitorInfoVO.getVisitorId());
        visitor.setVisitorName(visitorInfoVO.getVisitorName());
        visitor.setIdCardNumber(visitorInfoVO.getIdCardNumber());
        visitor.setVisitTime(visitorInfoVO.getVisitTime());
        visitor.setReason(visitorInfoVO.getReason());

        // 根据被访人姓名查询对应的用户ID
        String visitedPersonName = visitorInfoVO.getVisitedPersonName();
        if (visitedPersonName != null && !visitedPersonName.isEmpty()) {
            LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Users::getRealName, visitedPersonName);
            Users user = usersService.getOne(queryWrapper);
            if (user != null) {
                visitor.setVisitedUserId(user.getUserId());
            } else {
                // 如果找不到对应的用户，设置一个默认值
                visitor.setVisitedUserId(1); // 假设ID为1的用户是系统默认用户
            }
        } else {
            // 如果没有提供被访人姓名，设置一个默认值
            visitor.setVisitedUserId(1); // 假设ID为1的用户是系统默认用户
        }

        visitorsService.updateById(visitor);
        return R.success("来访记录更新成功");
    }
}
